<?php
/**
 * mock_fmw_api
 * FmwJDCZController.php
 * @author: Heze
 * Date: 2024/6/18 16:21
 */

namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class FmwJDCZController extends Controller
{
    protected $requestParams = [];

    public function index(Request $request)
    {
        $method = $request->get('method');
        $method = str_replace('.', '_', $method);

        if (!method_exists($this, $method)) {
            echo sprintf("[%s] mock function not exists", $method);
            exit;
        }
        $this->requestParams = json_decode($request->get('360buy_param_json'), true);

        return $this->$method($request);
    }

    private function _toResponseData($responseKey, $result)
    {
        return [
            $responseKey => [
                'result' => array_merge($result, [
                    "total" => "1",
                    "success" => "true",
                    "errorCode" => "0",
                    "errorMsg" => "成功"
                ])
            ],
        ];
    }

    // 生产中心获取订单列表
    public function jingdong_yip_production_orderList()
    {
        $order = [
            "refundSourceFlag" => "1",
            "totalPrice" => "100.00",
            "coId" => date('YmdHis') . rand(1000, 9999),
            "remark" => "订单备注文案",
            "cityId" => "2824",
            "townId" => "51919",
            "roId" => "1030023",
            "orgId" => "108",
            "productStageName" => "待生产",
            "poId" => "1030043",
            "vendorCode" => "fsdjzh",
            "paymentType" => 4,
            "orderState" => 3,
            "xid_buyer" => "客户的pin",
            "orderCreateDate" => time(),
            "pin" => "客户的pin",
            "cityName" => "保定市",
            "totalPurchasePrice" => "100.00",
            "countyId" => "156",
            "vendorRemark" => "商家备注的文案",
            "tel" => "010*******1",
            "totalCarriage" => "6.00",
            "open_id_buyer" => "客户的pin",
            "email" => "ijd@jd.com",
            "oaid" => "Qq1n94pda1EQrStSqtaqT3A4GGEDi63Mfrz1ay7EAcbCZo1a2YNR2PaCwwY5N6UJnTHYVykvsEbkG16Zd2urHXtJsqMLrSjnqvnDixd2A6Afmqzc9mgtZXiw2CJajYrWqXJtVcbhDXQGhqS3UYspUq6Mi9VEBmQzbeYgnfwwoc3MMGSF1vhPTXvfJe6QwGF",
            "countyName" => "行唐县",
            "zip" => "100026",
            "reduce" => "10.00",
            "townName" => "仁厚镇",
            "address" => "北京市海淀区******",
            "orgName" => "集团",
            "productStageId" => "6",
            "pay" => "100.00",
            "storeId" => "980",
            "provinceId" => "2",
            "presale" => "1",
            "customerName" => "张**",
            "deliverId" => "6",
            "isJdexpress" => "1",
            "phone" => "13300000011",
            "modifiedDate" => date('Y-m-d H:i:s'),
            "provinceName" => "河北",
            "deliverName" => "北京定制仓"
        ];

        return $this->_toResponseData('jingdong_yip_production_orderList_responce', [
            "orderBaseEntityList" => [$order],
        ]);
    }

    // C2M个性定制的订单详情接口
    public function jingdong_yip_production_orderDetail()
    {
        $orderDetails = [];
        foreach (range(0, rand(1, 2)) as $item) {
            $price = rand(1000, 3999);
            $quantity = rand(1, 5);
            $orderDetails[] = [
                "skuName" => "手机" . Str::random(6),
                "finalSalePrice" => $price,
                "salePrice" => $price + 300,
                "totalPrice" => $price * $quantity,
                "finalTotalPrice" => $price * $quantity,
                "upc" => date('His') . Str::random(6),
                "model" => "R21C/L",
                "purchasePrice" => $price - 300,
                "sku" => date('His') . $price,
                "poId" => date('YmdHis'),
                "skuCount" => $quantity
            ];
        }

        return $this->_toResponseData('jingdong_yip_production_orderDetail_responce', [
            'orderDetailInfoEntityList' => $orderDetails,
        ]);
    }


    public function jingdong_yip_order_getOrderCustomeInfos()
    {
        $price = rand(100, 999);
        $exts = [
            ['code' => 'SALE_PRICE', 'value' => $price],
            ['code' => 'IS_PURCHASERANGE_ENABLED', 'value' => 0],
            ['code' => 'B_PURCHASE_PRICE', 'value' => $price - 50],
            ['code' => 'TEXT_DESCRIPTION', 'value' => '珠光白-56P-印刷书本' . Str::random(6)],
            ['code' => 'IMAGE_URL', 'value' => ''],
        ];

        if ($this->requestParams['skuId'] % 2 == 0) {
            $exts[] = ['code' => 'MATERIAL_CODE', 'value' => Str::random(12)];
        }

        $value = [
            "ext" => $exts,
            "priceSource" => 2,
            "name" => "珠光白-56页",
            "attrValueNum" => 1,
            "id" => 247338,
            "priceCount" => 13,
            "selected" => 1
        ];

        $customParameter = [
            "extend" => [],
            "fe_code" => "fe_material",
            "values" => [$value],
            "name" => "款式",
            "id" => 1636,
            "componentAttrType" => 1,
            "skuCustomAttrRules" => [],
            "type" => 2,
            "required" => 1,
            "order" => 1
        ];

        $result = [
            "orderId" => $this->requestParams['orderId'],
            "canvasProductObj" => [],
            "customParameters" => [$customParameter],
            "skuId" => $this->requestParams['skuId'],
        ];

        $result2 = $result;
        $result2['orderId'] = $this->requestParams['orderId'] . $price;
        $result2['skuId'] = $this->requestParams['skuId'] . $price;
        $result['customParameters'][] = $customParameter;

        return [
            'jingdong_yip_order_getOrderCustomeInfos_responce' => [
                "dataResult" => [
                    'result' => [$result, $result2],
                ],
                "code" => "0"
            ],
        ];
    }

    public function jingdong_dropship_dps_searchsingleorder()
    {
        $list = [
            "cost" => "10",
            "purchaseOrderId" => "1234567",
            "commodityNum" => "5",
            "upc" => "待完善",
            "discount" => "10",
            "jdPrice" => "20",
            "skuId" => "67890",
            "commodityName" => "袜子"
        ];

        $resultSingleDto = [
            "customOrderId" => sprintf('jdcz%s%s', date('YmdHis'), Str::random(6)),
            "sendPay" => "0100200",
            "refundSourceFlag" => "1",
            "updateDate" => "1649334358000",
            "consolidatorInfo" => "{cityId:1607,consolidator:795128,countryId:4773,detailAddr:广东深圳市宝安区福海街道福园一路201A,name:国际物流旗舰店,phone:13500000000,proviceId:19,townId:47415}",
            "orderRemark" => "蓝色",
            "orderState" => "10",
            "extInfo" => "{}",
            "consigneeName" => "张**",
            "orderCreateDate" => time(),
            "orderTime" => "2021-03-03 12:01:09",
            "pin" => "jd12312421321",
            "cityName" => "廊坊",
            "isNotice" => "0",
            "parentOrderId" => "78627163127",
            "operatorState" => "10",
            "totalCarriage" => "15",
            "pay" => "95.0",
            "open_id_buyer" => "jd12312421321",
            "email" => "xx@jd.com",
            "oaid" => "Qq1n94pda1EQrStSqtaqT3A4GGEDi63Mfrz1ay7EAcbCZo1a2YNR2PaCwwY5N6UJnTHYVykvsEbkG16Zd2urHXtJsqMLrSjnqvnDixd2A6Afmqzc9mgtZXiw2CJajYrWqXJtVcbhDXQGhqS3UYspUq6Mi9VEBmQzbeYgnfwwoc3MMGSF1vhPTXvfJe6QwGF",
            "createDate" => "2021-03-03 12:01:09",
            "countyName" => "某县",
            "vendorStoreName" => "测试仓",
            "orderSource" => "CPS",
            "townName" => "某镇",
            "address" => "北京市海淀区******",
            "paymentCategory" => "NON_COD",
            "postcode" => "100000",
            "telephone" => "010*******1",
            "promisePickDate" => date('Y-m-d H:i:s', strtotime('+3 day')), // 承诺最晚揽件时间
            "memoByVendor" => "优先发",
            "outPlatformOrderInfo" => [
                "outPlatformOrderId" => "1111",
                "whereEnc" => "加密地址",
                "outPlatformShopId" => "id",
                "outPlatformParentOrderId" => "2222",
                "nameEnc" => "加密姓名",
                "mobileEnc" => "加密电话"
            ],
            "orderDetailList" => [
                $list
            ],
            "phone" => "133*******1",
            "reduceCount" => "20",
            "opPickDate" => "2024-05-20 00:00:00",
            "provinceName" => "河北",
            "storeInfo" => [
                "storeAddress" => "广东深圳市光明区马田街道新庄社区华发路商业街B栋103",
                "storePhone" => "19924512586",
                "storeName" => "【京东养车】公明松白路店",
                "storeId" => "1014077315"
            ],
            "opDeliveredDate" => "2024-05-20 00:00:00",
            "expectedDeliveryTime" => "2021-03-03 12:01:09",
            "paymentCategoryDispName" => "在线支付",
            "vendorStoreId" => "12121"
        ];

        return [
            'jingdong_dropship_dps_searchsingleorder_responce' => [
                'searchSingleResult' => [
                    "recordCount" => "1",
                    "errorCode" => "调用失败，返回异常码例如：201",
                    "resultSingleDto" => $resultSingleDto,
                    "message" => "返回异常消息，例如：内部处理错误。",
                    "status" => "1"
                ],
            ],
        ];
    }

    public function jingdong_vc_item_product_get()
    {
        $propInfos = [
            "——" => [
                "vid" => "1121",
                "vname" => "规格参数",
                "prop_values" => [],
                "pid" => "1",
                "remark" => "自定义",
                "inputType" => "1"
            ]
        ];

        $sku = [
            '——' => [
                "dim1_val" => "红色",
                "length" => "10",
                "weight" => "3",
                "upc" => "12225",
                "member_price" => "5762.23",
                "uuid" => "121-1221-121",
                "skuName" => "sku的商品名称",
                "itemNum" => "23232",
                "dim2_sort" => "1",
                "skuShortTitle" => "盖亚子sku的短标题",
                "other_sale_attribute" => [],
                "dim1_sort" => "1",
                "purchase_price" => "5862.23",
                "width" => "46",
                "market_price" => "5962.23",
                "dim2_val" => "XL",
                "skuId" => "10001212",
                "height" => "13"
            ]
        ];

        return [
            'jingdong_vc_item_product_get_responce' => [
                'jos_result_dto' => [
                    "count" => "10",
                    "return_message" => "执行成功",
                    "single_obj" => [
                        "vendor_code" => "bjgys",
                        "gifts_goods" => "0",
                        "pkgInfo" => "USB线 × 1、AV线 × 1",
                        "pc_decoration_html" => "1",
                        "saler_name" => "北京销售员",
                        "videoId" => "1001",
                        "en_brand" => "Jd",
                        "shortTitle" => "测试商品",
                        "mobile_decoration_html" => "1",
                        "prop_infos_list" => [$propInfos],
                        "saler_code" => "bjxsy",
                        "modifyTime" => "2015-11-13 23:59:59",
                        "warranty" => "五年质保",
                        "model" => "x",
                        "tel" => "01085655125",
                        "sku_unit" => "台",
                        "isFlashPurchase" => "1",
                        "cid1" => "1342",
                        "height" => "13",
                        "product_oil_number" => "4.0123",
                        "upc" => "12225",
                        "weight" => "3",
                        "vendor_name" => "北京供应商",
                        "brand_name" => "京东",
                        "ext_propI_infos_list" => [],
                        "brand_id" => "1025",
                        "wreadme" => "1",
                        "aftersales" => "售后信息",
                        "salerDeptId" => "1221",
                        "issn" => "1",
                        "name" => "京东电脑",
                        "zh_brand" => "京东",
                        "purchase_price" => "5862.23",
                        "market_price" => "5962.23",
                        "pc_template_html" => "1",
                        "catalogerCode" => "bjsgy",
                        "spwq" => "1",
                        "skuList" => [$sku],
                        "flashProductor" => "bjcpsh",
                        "design_concept" => "设计理念值",
                        "member_price" => "5762.23",
                        "isOverseaPurchase" => "3",
                        "packing" => "1",
                        "title" => "面膜视频",
                        "original_place" => "大连",
                        "full_category_name1" => "电子-电脑类",
                        "shelf_life" => "1",
                        "sub_categories" => [],
                        "itemNum" => "SKUA00003",
                        "purchaser_name" => "北京采购员",
                        "dangerGoods" => "0",
                        "product_oil_unit" => "L",
                        "cid_name1" => "电脑类",
                        "spuProductName" => "产品名称",
                        "wareId" => "1056",
                        "after_sale_desc" => "售后保障图文详情字符串",
                        "stores" => [],
                        "length" => "10",
                        "catalogerName" => "北京上柜员",
                        "intro_mobile" => "1",
                        "salesRatio" => "1",
                        "purchaser_code" => "bjcgy",
                        "pack_type" => "1",
                        "intro_html" => "1",
                        "sysp" => "0",
                        "service" => "服务信息",
                        "isJIT" => "1",
                        "width" => "46",
                        "store_property" => "1",
                        "spuId" => "10001",
                        "web_site" => "www.jd.com",
                        "salerDeptName" => "产品经理"
                    ],
                    "is_success" => "true",
                    "return_code" => "101"
                ]
            ]
        ];
    }

    public function jingdong_omnic_order_query_orderList()
    {
        $orderId = $this->requestParams['data']['orderId'] ?? date('YmdHis').rand(1000, 9999);

        $orderDetail = [
            "skuUuid" => "1012_d1I2qi1487632661060173824",
            "orderId" => $orderId,
            "num" => 2,
            "extendJson" => "{\"cid\":21458}",
            "salesChannelSkuId" => "5264152",
            "skuAmount" => 600.00,
            "transactionPrice" => 300,
            "skuPrice" => 300,
            "upc" => "5264152",
            "weight" => 0.07,
            "skuName" => "5J （Cinco Jotas）西班牙进口伊比利亚5J火腿前腿切片 70g 橡果饲养 源头直发",
            "sequenceNo" => 2830929053,
            "tenantId" => 241758,
            "outSkuId" => "5264152",
            "bulk" => 238,
            "checkSn" => 0,
            "skuId" => "5264152"
        ];

        $order = [
            "orderDetailList" => [
                $orderDetail
            ],
            "orderShip" => [
                "orderId" => $orderId,
                "expectEndTime" => intval(microtime(true) * 1000),
                "expectStartTime" => intval(microtime(true) * 1000),
                "addressLevel2Name" => "连云港市",
                "consigneeMobileEnc" => "AAT50iRMl+5xFjX10tQfA5TLCfJT4ITWjJGapfDuhdK3bThh9iY=",
                "consigneePhoneEnc" => "AAT50iRMl+5xFjX10tQfA5TLCfJT4ITWjJGapfDuhdK3bThh9iY=",
                "sequenceNo" => 1690620326,
                "carrierName" => "",
                "deliveryMode" => 7,
                "deliveryAddress" => "江苏连云港市灌云县******",
                "addressLevel3Name" => "灌云县",
                "consigneePhone" => "185*******6",
                "consigneeMobile" => "180*******5",
                "addressLevel4" => 24023,
                "addressLevel2" => 919,
                "addressLevel3" => 921,
                "lat" => 34.30424,
                "oaid" => "YzIxMDk0ABT5Yz05DTH47QCKVJNOXZu1Yjk1MpciiVucZUhuUymulFq2aOXmweW8VAJTg1yiysVMcBWvWX7oVPrQPNIVHAUF1n+io7l9R1f5RWtc3gQjjdQXwCT45/mbqYqBSQC/CrMm4P1azjwJEw/GiDrrhZrpK8IQlA==",
                "addressLevel1" => 12,
                "consigneeEnc" => "AAT50iRMl+5xFjX10tQfA5TLTlq+/eixS7Z56beQ7b8MMv7pt7M=",
                "consignee" => "北**",
                "lng" => 119.251206,
                "carrierType" => 0,
                "addressLevel4Name" => "伊山镇",
                "deliveryAddressEnc" => "AAT50iRMl+5xFjX10tQfA5TLnT9aZG9KoiR9jVGzoTdnOWkplT8eralXxgX0phw9IjjkuzbYEKakDd5Od8WBAHQMjweSADoTA50bM7Bca43i8dxGsjN4ZJDveFmuit8nC+IXUNO6",
                "addressLevel1Name" => "江苏",
                "codTimeType" => 0,
                "tenantId" => 241758
            ],
            "orderInfo" => [
                "orderType" => 0,
                "forceDown" => 0,
                "sendpay" => "",
                "orderId" => $orderId,
                "paymentMode" => 1,
                "outerWarehouseId" => "shxcxd5J2024",
                "vendorCode" => "shxcxd",
                "mpfStoreId" => "1016093249",
                "sequenceNo" => 1691054557,
                "commitTime" => intval(microtime(true) * 1000),
                "warehouseId" => 11528994,
                "is_valid" => 1,
                "salesChannelOrderId" => $orderId,
                "customerId" => "jd_zbtszFQtSamD",
                "tenantId" => 241758,
                "currency" => "CNY",
                "paymentTime" => intval(microtime(true) * 1000),
                "sendPayMap" => "",
                "checkSn" => 0,
                "tradeType" => 10,
                "status" => 300
            ]
        ];

        return [
            'jingdong_omnic_order_query_orderList_responce' => [
                "result" => [
                    "data" => [
                        "data" => [$order],
                        "totalItem" => $this->requestParams['data']['currentPage'] > 1 ? 0 : 1,
                        "pageNo" => 1,
                        "pageSize" => 50
                    ],
                    "success" => true
                ],
                "request_id" => "e835e32a8ec0405395f7957473924990",
                "code" => "0"
            ]
        ];
    }

    //  解码 OAID 返回收件人信息
    public function jingdong_jos_order_oaid_decrypt(Request $request)
    {
        $data = [];
        $orderInfos = $this->requestParams['getReceiverInfoListReqVO']['orderInfos'] ?? [];
        foreach ($orderInfos as $orderInfo) {
            $data[] = [
                "customerPhone" => "13311111100",
                "address" => "北京市朝阳区合生汇写字楼",
                "privacyProtection" => "true",
                "orderId" => $orderInfo['orderId'],
                "consMobilePhone" => "18888888811",
                "expiration" => date('Y-m-d H:i:s'),
                "consMobilePhoneFuzzy" => "13311111100",
                "oaid" => $orderInfo['oaid'],
                "customerName" => "张三丰"
            ];
        }

        $code = 200;
        $message = 'success';

        // 解密失败
//        $code = 406;
//        $data = [];
//        $message = 'appKey：3E43376ECD473CEE315D73C2ABC778CA venderId：667324 请商家使用京东快递、无界面单发货，京东打印插件打印面单。如需明文，请使用虚拟号（虚拟号支持拨打11位明文转4位分机号联系客户和个别快递柜投递场景，请商家根据业务场景谨慎使用）';

//        return Response('解密失败！', 400);

        return [
            'jingdong_jos_order_oaid_decrypt_responce' => [
                'returnType' => [
                    "code" => $code,
                    "data" => $data,
                    "requestId" => "12312321",
                    "message" => $message
                ],
            ],
        ];
    }
}
